Parkinson's disease, or simply Parkinson's, is a long-term degenerative disorder of the central nervous system that mainly affects the motor system. As the disease worsens, non-motor symptoms become more common. The symptoms usually emerge slowly. Early in the disease, the most obvious symptoms are shaking, rigidity, slowness of movement, and difficulty with walking.Thinking and behavioral problems may also occur. Dementia becomes common in the advanced stages of the disease.Depression and anxiety are also common, occurring in more than a third of people with PD. Other symptoms include sensory, sleep, and emotional problems. The main motor symptoms are collectively called "parkinsonism", or a "parkinsonian syndrome".
The cause of Parkinson's disease is unknown, but is believed to involve both genetic and environmental factors. Those with a family member affected are more likely to get the disease themselves.There is also an increased risk in people exposed to certain pesticides and among those who have had prior head injuries, while there is a reduced risk in tobacco smokers and those who drink coffee or tea. The motor symptoms of the disease result from the death of cells in the substantia nigra, a region of the midbrain. This results in not enough dopamine in this region of the brain.The cause of this cell death is poorly understood, but it involves the build-up of proteins into Lewy bodies in the neurons. Diagnosis of typical cases is mainly based on symptoms, with tests such as neuroimaging used to rule out other diseases.
There is no cure for Parkinson's disease
pip install pandas-profiling
pip install empiricaldist;
pip install plotly_express;
import warnings
warnings.filterwarnings('ignore')
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import datetime as dt
import math
import pycountry
import pycountry_convert as pc
from plotly.subplots import make_subplots
import plotly_express as px
import plotly.graph_objects as go
import plotly.figure_factory as ff
from plotly.subplots import make_subplots
import empiricaldist as emp
%matplotlib inline
sns.set_style('darkgrid')
# Defining ecdf Function for Cumilative Distribution Function
def ecdf(data):
"""Compute ECDF for a one-dimensional array of measurements."""
#credits DataCamp Justin Bois
# Number of data points: n
n = len(data)
# x-data for the ECDF: x
x = np.sort(data)
# y-data for the ECDF: y
y = np.arange(1, n+1) / n
return x, y
# Defining ecdf plotting function between two variables
def ecdf_plot(c1,c2,t1='First set',t2='Second set'):
"""Plot ECDF for a one-dimensional array of measurements between two variables."""
#Using ecdf to compute the CDF
x1,y1 = list(ecdf(c1))
x,y = list(ecdf(c2))
#Create a subplot to fit two axis
fig = make_subplots(rows=1, cols=2,subplot_titles=(f'CDF of {t1}', f'CDF of {t2}'))
#add first plot of Budget
fig.add_trace(
go.Scatter(x= x1,y = y1,name = f'CDF of {t1}'),
row=1, col=1
)
#add second plot of Revenue
fig.add_trace(
go.Scatter(x = x,y = y,name = f'CDF of {t2}'),
row=1, col=2
)
#control title and figure dimentions
fig.update_layout(height=500, width=1000, title_text="Cumulative distribution functions")
fig.show()
The dataset was created by Max Little of the University of Oxford, in collaboration with the National Centre for Voice and Speech, Denver, Colorado, who recorded the speech signals. The original study published the feature extraction methods for general voice disorders.
This dataset is composed of a range of biomedical voice measurements from 31 people, 23 with Parkinson's disease (PD). Each column in the table is a particular voice measure, and each row corresponds one of 195 voice recording from these individuals ("name" column). The main aim of the data is to discriminate healthy people from those with PD, according to "status" column which is set to 0 for healthy and 1 for PD.
The data is in ASCII CSV format. The rows of the CSV file contain an instance corresponding to one voice recording. There are around six recordings per patient, the name of the patient is identified in the first column.For further information or to pass on comments, please contact Max Little (littlem '@' robots.ox.ac.uk).
Further details are contained in the following reference -- if you use this dataset, please cite: Max A. Little, Patrick E. McSharry, Eric J. Hunter, Lorraine O. Ramig (2008), 'Suitability of dysphonia measurements for telemonitoring of Parkinson's disease', IEEE Transactions on Biomedical Engineering (to appear).
#Importing datasets of Parkinson's
df = pd.read_csv('D:\DATASCIENCE\Project 3\Dataset\\parkinsons.csv')
display(df.head())
display(df.describe())
display(df.info())
Data does seem clean to proceed to EDA Phase with minimal to no cleaning, with no missing data or unmatching data types.
Preferably cleaning the 'name' column to discard of 'phonR01' prefix to further simplify the data.
As well as changing Status type from int to categorical variable.
# Changing Status type to categorical
df.status = df.status.astype('category')
# Simplifying name column
df.replace(to_replace ='phon_R01_', value = '', regex = True, inplace = True)
ax = sns.heatmap(df.corr(method='spearman'))
plt.title('Correlation between features Using Spearman Method');
From previous analysis and visually exploring data some questions arised:-
1- Which of the 22 features are the most contributing to the status of the patient?
2- Which relationship between two features would produce a distinction between status 1 and 0?
Correlation diagram suggests thet PPE and MDVP:Fo and HNR are the most contributing features to status with either negative or positive correlation value.
PPE_1 = df[df.status == 1]['PPE']
PPE_0 = df[df.status == 0]['PPE']
fig = ecdf_plot(PPE_0,PPE_1,'PPE for Negative Patients','PPE for Positive Patients')
fig = px.histogram(df, x = 'PPE', color= df.status, marginal = "box", title = 'Histogram of PPE Distribution over both Status')
# Overlay both histograms
fig.update_layout(barmode='overlay')
# Reduce opacity to see both histograms
fig.update_traces(opacity=0.75)
CDF shows distribution of values throughout the feature with respect to the status of the patient which shows significant difference between both distributions.
Histogram shows another perspective of the distribution of the feature with PPE higher than 0.3 signifies positive status.
Box plot shows a clearer picture of the feature at question showing values higher than 0.21 are most probable to be positive.
PPE_1 = df[df.status == 1]['MDVP:Fo(Hz)']
PPE_0 = df[df.status == 0]['MDVP:Fo(Hz)']
ecdf_plot(PPE_0,PPE_1,'MDVP:Fo(Hz) for Negative Patients','MDVP:Fo(Hz) for Positive Patients')
fig = px.histogram(df, x = 'MDVP:Fo(Hz)', color= df.status, marginal = "box", title = 'Histogram of MDVP:Fo Distribution over both Status')
# Overlay both histograms
fig.update_layout(barmode='overlay')
# Reduce opacity to see both histograms
fig.update_traces(opacity=0.75)
CDF shows distribution of values throughout the feature with respect to the status of the patient which shows significant difference between both distributions specially in values lower than 110 Hz.
Histogram shows another perspective of the distribution of the feature with Fo (Hz) higher than 220 Hz signifies Negative status.
Box plot shows a clearer picture of the feature at question showing values lower than 120 Hz are most probable to be positive.
PPE_1 = df[df.status == 1]['HNR']
PPE_0 = df[df.status == 0]['HNR']
ecdf_plot(PPE_0,PPE_1,'HNR for Negative Patients','HNR for Positive Patients')
fig = px.histogram(df, x = 'HNR', color= df.status, marginal = "box", title = 'Histogram of HNR Distribution over both Status')
# Overlay both histograms
fig.update_layout(barmode='overlay')
# Reduce opacity to see both histograms
fig.update_traces(opacity=0.75)
CDF shows High difference between the two variables at higher percentiles and lower ones, with mid range having similarities.
Histogram shows overlapping statuses in midrange 17 and 30 yet significant difference between both status at values lower than 18.
Box plot shows a clearer picture of the feature at question showing values higher than 30 are most probable to be negative while values lower than 17 are most probably positive.
Plotting a scatter plot matrix between all features to visually distinct which features could produce the most clear differentiable statuses.
Also taking into account correlation matrix as deduced above and their EDA.
sns.pairplot(df, hue="status");
Deduced from the above figure that MDVP:Fo(HZ) has the most differentiable measurement more over when correlated with HNR and PPE results are very interesting.
fig = px.scatter(df, x ='HNR',y = 'MDVP:Fo(Hz)', color = 'status', title = 'Relationship between MDVP:Fo & HNR wrt Status')
fig
fig = px.scatter(df, x ='PPE',y = 'MDVP:Fo(Hz)', color = 'status', title = 'Relationship between MDVP:Fo & PPE wrt Status')
fig
from sklearn.model_selection import train_test_split
from sklearn import preprocessing
from sklearn.preprocessing import MinMaxScaler
from sklearn.model_selection import cross_val_score
from sklearn.linear_model import LogisticRegression
from sklearn.svm import SVC
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import RandomForestClassifier
from sklearn.ensemble import AdaBoostClassifier
from sklearn.model_selection import StratifiedKFold
from sklearn.metrics import confusion_matrix, accuracy_score, recall_score, roc_curve, auc
import xgboost as xgb
Defining Target for the model and features
Y = df['status'].values # Target for the model
X = df[['MDVP:Fo(Hz)', 'MDVP:Fhi(Hz)', 'MDVP:Flo(Hz)', 'MDVP:Jitter(%)','MDVP:Jitter(Abs)', 'MDVP:RAP', 'MDVP:PPQ', 'Jitter:DDP','MDVP:Shimmer', 'MDVP:Shimmer(dB)', 'Shimmer:APQ3', 'Shimmer:APQ5','MDVP:APQ', 'Shimmer:DDA', 'NHR', 'HNR', 'RPDE', 'DFA','spread1', 'spread2', 'D2', 'PPE']]
# Spliting data to test and train sets
X_train, X_test, Y_train, Y_test = train_test_split(X, Y, random_state=42)
# Normalizing Data using MinMaxScaler
scaler = MinMaxScaler().fit(X_train)
X_train_scaled = scaler.transform(X_train)
X_test_scaled = scaler.transform(X_test)
Defining list to store Performance Metrics
performance = [] # list to store all performance metric
lr_best_score = 0
lr_kfolds = 5 # set the number of folds
# Finding the Best lr Model
for c in [0.001, 0.1, 1, 4, 10, 100]:
logRegModel = LogisticRegression(C=c)
# perform cross-validation
scores = cross_val_score(logRegModel, X_train, Y_train, cv = lr_kfolds, scoring = 'accuracy') # Get recall for each parameter setting
# compute mean cross-validation accuracy
score = np.mean(scores)
# Find the best parameters and score
if score > lr_best_score:
lr_best_score = score
lr_best_parameters = c
# rebuild a model on the combined training and validation set
SelectedLogRegModel = LogisticRegression(C = lr_best_parameters).fit(X_train_scaled, Y_train)
# Model Test
lr_test_score = SelectedLogRegModel.score(X_test_scaled, Y_test)
# Predicted Output of Model
PredictedOutput = SelectedLogRegModel.predict(X_test_scaled)
# Extracting sensitivity & specificity from ROC curve to measure Performance of the model
lr_fpr, lr_tpr, lr_thresholds = roc_curve(Y_test, PredictedOutput, pos_label=1)
# Using AUC of ROC to validate models based on a single score
lr_test_auc = auc(lr_fpr, lr_tpr)
# Output Printing Scores
print("Best accuracy on validation set is:", lr_best_score)
print("Best parameter for regularization (C) is: ", lr_best_parameters)
print("Test accuracy with best C parameter is", lr_test_score)
print("Test AUC with the best C parameter is", lr_test_auc)
# Appending results to performance list
m = 'Logistic Regression'
performance.append([m, lr_test_score, lr_test_auc, lr_fpr, lr_tpr, lr_thresholds])
svm_best_score = 0
svm_kfolds = 5
for c_paramter in [0.001, 0.01, 0.1,6, 10, 100, 1000]: #iterate over the values we need to try for the parameter C
for gamma_paramter in [0.001, 0.01, 0.1,5, 10, 100, 1000]: #iterate over the values we need to try for the parameter gamma
for k_parameter in ['rbf', 'linear', 'poly', 'sigmoid']: # iterate over the values we need to try for the kernel parameter
svmModel = SVC(kernel=k_parameter, C=c_paramter, gamma=gamma_paramter) #define the model
# perform cross-validation
scores = cross_val_score(svmModel, X_train_scaled, Y_train, cv = svm_kfolds, scoring='accuracy')
# the training set will be split internally into training and cross validation
# compute mean cross-validation accuracy
score = np.mean(scores)
# if we got a better score, store the score and parameters
if score > svm_best_score:
svm_best_score = score #store the score
svm_best_parameter_c = c_paramter #store the parameter c
svm_best_parameter_gamma = gamma_paramter #store the parameter gamma
svm_best_parameter_k = k_parameter
# rebuild a model with best parameters to get score
SelectedSVMmodel = SVC(C = svm_best_parameter_c, gamma = svm_best_parameter_gamma, kernel = svm_best_parameter_k).fit(X_train_scaled, Y_train)
# Model Test
svm_test_score = SelectedSVMmodel.score(X_test_scaled, Y_test)
# Predicted Output of Model
PredictedOutput = SelectedSVMmodel.predict(X_test_scaled)
# Extracting sensitivity & specificity from ROC curve to measure Performance of the model
svm_fpr, svm_tpr, svm_thresholds = roc_curve(Y_test, PredictedOutput, pos_label=1)
# Using AUC of ROC to validate models based on a single score
svm_test_auc = auc(svm_fpr, svm_tpr)
# Output Printing Scores
print("Best accuracy on cross validation set is:", svm_best_score)
print("Best parameter for c is: ", svm_best_parameter_c)
print("Best parameter for gamma is: ", svm_best_parameter_gamma)
print("Best parameter for kernel is: ", svm_best_parameter_k)
print("Test accuracy with the best parameters is", svm_test_score)
print("Test AUC with the best parameter is", svm_test_auc)
# Appending results to performance list
m = 'SVM'
performance.append([m, svm_test_score, svm_test_auc, svm_fpr, svm_tpr, svm_thresholds])
dt_best_score = 0
dt_kfolds = 10
for md in range(1, 9): # iterate different maximum depth values
# train the model
treeModel = DecisionTreeClassifier(random_state=0, max_depth=md, criterion='gini')
# perform cross-validation
scores = cross_val_score(treeModel, X_train_scaled, Y_train, cv = dt_kfolds, scoring='accuracy')
# compute mean cross-validation accuracy
score = np.mean(scores)
# if we got a better score, store the score and parameters
if score > dt_best_score:
dt_best_score = score
dt_best_parameter = md
# Rebuild a model on the combined training and validation set
SelectedDTModel = DecisionTreeClassifier(max_depth = dt_best_parameter).fit(X_train_scaled, Y_train )
# Model Test
dt_test_score = SelectedDTModel.score(X_test_scaled, Y_test)
# Predicted Output of Model
PredictedOutput = SelectedDTModel.predict(X_test_scaled)
# Extracting sensitivity & specificity from ROC curve to measure Performance of the model
dt_fpr, dt_tpr, dt_thresholds = roc_curve(Y_test, PredictedOutput, pos_label=1)
# Using AUC of ROC to validate models based on a single score
dt_test_auc = auc(dt_fpr, dt_tpr)
# Output Printing Scores
print("Best accuracy on validation set is:", dt_best_score)
print("Best parameter for the maximum depth is: ", dt_best_parameter)
print("Test accuracy with best parameter is ", dt_test_score)
print("Test AUC with the best parameter is ", dt_test_auc)
# Appending results to performance list
m = 'Decision Tree'
performance.append([m, dt_test_score, dt_test_auc, dt_fpr, dt_tpr, dt_thresholds])
print("Feature importance: ")
features = np.array([X.columns.values.tolist(), list(SelectedDTModel.feature_importances_)]).T
for i in features:
print(f'{i[0]} : {i[1]}')
rf_best_score = 0
rf_kfolds = 5
for M in range(2, 15, 2): # combines M trees
for d in range(1, 9): # maximum number of features considered at each split
for m in range(1, 9): # maximum depth of the tree
# train the model
# n_jobs(4) is the number of parallel computing
forestModel = RandomForestClassifier(n_estimators = M, max_features = d, n_jobs = 4,max_depth = m, random_state = 0)
# perform cross-validation
scores = cross_val_score(forestModel, X_train_scaled, Y_train, cv = rf_kfolds, scoring = 'accuracy')
# compute mean cross-validation accuracy
score = np.mean(scores)
# if we got a better score, store the score and parameters
if score > rf_best_score:
rf_best_score = score
rf_best_M = M
rf_best_d = d
rf_best_m = m
# Rebuild a model on the combined training and validation set
SelectedRFModel = RandomForestClassifier(n_estimators=rf_best_M, max_features=rf_best_d,max_depth=rf_best_m, random_state=0).fit(X_train_scaled, Y_train )
# Model Test
rf_test_score = SelectedRFModel.score(X_test_scaled, Y_test)
# Predicted Output of Model
PredictedOutput = SelectedRFModel.predict(X_test_scaled)
# Extracting sensitivity & specificity from ROC curve to measure Performance of the model
rf_fpr, rf_tpr, rf_thresholds = roc_curve(Y_test, PredictedOutput, pos_label=1)
# Using AUC of ROC to validate models based on a single score
rf_test_auc = auc(rf_fpr, rf_tpr)
# Output Printing Scores
print("Best accuracy on validation set is:", rf_best_score)
print("Best parameters of M, d, m are: ", rf_best_M, rf_best_d, rf_best_m)
print("Test accuracy with the best parameters is", rf_test_score)
print("Test AUC with the best parameters is:", rf_test_auc)
# Appending results to performance list
m = 'Random Forest'
performance.append([m, rf_test_score, rf_test_auc, rf_fpr, rf_tpr, rf_thresholds])
ada_best_score = 0
ada_kfolds = 5
for M in range(2, 15, 2): # combines M trees
for lr in [0.0001, 0.001, 0.01, 0.1, 1,2,3]:
# train the model
boostModel = AdaBoostClassifier(n_estimators=M, learning_rate=lr, random_state=0)
# perform cross-validation
scores = cross_val_score(boostModel, X_train_scaled, Y_train, cv = ada_kfolds, scoring = 'accuracy')
# compute mean cross-validation accuracy
score = np.mean(scores)
# if we got a better score, store the score and parameters
if score > ada_best_score:
ada_best_score = score
ada_best_M = M
ada_best_lr = lr
# Rebuild a model on the combined training and validation set
SelectedBoostModel = AdaBoostClassifier(n_estimators=ada_best_M, learning_rate=ada_best_lr, random_state=0).fit(X_train_scaled, Y_train )
# Model Test
ada_test_score = SelectedBoostModel.score(X_test_scaled, Y_test)
# Predicted Output of Model
PredictedOutput = SelectedBoostModel.predict(X_test_scaled)
# Extracting sensitivity & specificity from ROC curve to measure Performance of the model
ada_fpr, ada_tpr, ada_thresholds = roc_curve(Y_test, PredictedOutput, pos_label=1)
# Using AUC of ROC to validate models based on a single score
ada_test_auc = auc(ada_fpr, ada_tpr)
# Output Printing Scores
print("Best accuracy on validation set is:", ada_best_score)
print("Best parameter of M is: ", ada_best_M)
print("best parameter of LR is: ", ada_best_lr)
print("Test accuracy with the best parameter is", ada_test_score)
print("Test AUC with the best parameters is:", ada_test_auc)
# Appending results to performance list
m = 'AdaBoost'
performance.append([m, ada_test_score, ada_test_auc, ada_fpr, ada_tpr, ada_thresholds])
xgb_best_score = 0
xgb_kfolds = 5
for n in [2,4,6,8,10]: #iterate over the values we need to try for the parameter n_estimators
for lr in [1.1,1.2,1.22,1.23,1.3]: #iterate over the values we need to try for the learning rate parameter
for depth in [2,4,6,8,10]: # iterate over the values we need to try for the depth parameter
XGB = xgb.XGBClassifier(objective = 'binary:logistic', max_depth=depth, n_estimators=n, learning_rate = lr) #define the model
# perform cross-validation
scores = cross_val_score(XGB, X_train_scaled, Y_train, cv = xgb_kfolds, scoring='accuracy')
# the training set will be split internally into training and cross validation
# compute mean cross-validation accuracy
score = np.mean(scores)
# if we got a better score, store the score and parameters
if score > xgb_best_score:
xgb_best_score = score #store the score
xgb_best_md = depth #store the parameter maximum depth
xgb_best_ne = n #store the parameter n_estimators
xgb_best_lr = lr #store the parameter learning rate
# rebuild a model with best parameters to get score
XGB_selected = xgb.XGBClassifier(objective = 'binary:logistic',max_depth=xgb_best_md, n_estimators=xgb_best_ne, learning_rate = xgb_best_lr).fit(X_train_scaled, Y_train)
# Model Test
xgb_test_score = XGB_selected.score(X_test_scaled, Y_test)
# Predicted Output of Model
PredictedOutput = XGB_selected.predict(X_test_scaled)
# Extracting sensitivity & specificity from ROC curve to measure Performance of the model
xgb_fpr, xgb_tpr, xgb_thresholds = roc_curve(Y_test, PredictedOutput, pos_label=1)
# Using AUC of ROC to validate models based on a single score
xgb_test_auc = auc(xgb_fpr, xgb_tpr)
# Output Printing Scores
print("Best accuracy on cross validation set is:", xgb_best_score)
print("Best parameter for maximum depth is: ", xgb_best_md)
print("Best parameter for n_estimators is: ", xgb_best_ne)
print("Best parameter for learning rate is: ", xgb_best_lr)
print("Test accuracy with the best parameters is", xgb_test_score)
print("Test AUC with the best parameters is:", xgb_test_auc)
# Appending results to performance list
m = 'XGB'
performance.append([m, xgb_test_score, xgb_test_auc, xgb_fpr, xgb_tpr, xgb_thresholds])
from sklearn.ensemble import VotingClassifier
# Logistic regression model
clf1 = LogisticRegression(C=lr_best_parameters).fit(X_train_scaled, Y_train)
# SVC Model
clf2 = SVC(C=svm_best_parameter_c, gamma=svm_best_parameter_gamma, kernel=svm_best_parameter_k,probability=True)
# DecisionTreeClassifier model
clf3 = DecisionTreeClassifier(max_depth=dt_best_parameter)
# Random Forest Classifier Model
clf4 = RandomForestClassifier(n_estimators=rf_best_M, max_features=rf_best_d,max_depth=rf_best_m, random_state=42)
# AdaBoostClassifier Model
clf5 = AdaBoostClassifier(n_estimators=ada_best_M, learning_rate=ada_best_lr, random_state=42)
# XGBoost Classifier Model
clf6 = xgb.XGBClassifier(objective = 'binary:logistic',max_depth=xgb_best_md, n_estimators=xgb_best_ne ,learning_rate = xgb_best_lr)
# Defining VotingClassifier
eclf1 = VotingClassifier(estimators=[ ('LogisticRegression', clf1), ('SVC', clf2),('DecisionTree',clf3),('Random Forest', clf4),('ADABoost',clf5),('XGBoost',clf6)], voting='hard')
# Fitting VotingClassifier
eclf1 = eclf1.fit(X_train_scaled, Y_train)
# Model Test
eclf_test_score = eclf1.score(X_test_scaled, Y_test)
# Predicted Output of Model
PredictedOutput = eclf1.predict(X_test_scaled)
# Extracting sensitivity & specificity from ROC curve to measure Performance of the model
eclf_fpr, eclf_tpr, eclf_thresholds = roc_curve(Y_test, PredictedOutput, pos_label=1)
# Using AUC of ROC to validate models based on a single score
eclf_test_auc = auc(eclf_fpr, eclf_tpr)
# Output Printing Scores
print("Test accuracy with the best parameters is", eclf_test_score)
print("Test AUC with the best parameters is:", eclf_test_auc)
# Appending results to performance list
m = 'ECLF'
performance.append([m, eclf_test_score, eclf_test_auc, eclf_fpr, eclf_tpr, eclf_thresholds])
result = pd.DataFrame(performance, columns=['Model', 'Accuracy', 'AUC', 'FPR', 'TPR', 'TH'])
df = result[['Model', 'Accuracy', 'AUC']]
results = df.sort_values('Accuracy',ascending = False)
display(results.style.background_gradient(cmap='Reds',subset=["Accuracy"]).background_gradient(cmap='Greens',subset=["AUC"]))